<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
    <title> - 天地维杰网</title>
    <meta name="keywords" content="系统架构,shutdown,不与天斗,Domino,博客,程序员,架构师,笔记,技术,分享,java,Redis">
    
    <meta property="og:title" content="">
    <meta property="og:site_name" content="天地维杰网">
    <meta property="og:image" content="/img/author.jpg"> 
    <meta name="title" content=" - 天地维杰网" />
    <meta name="description" content="天地维杰网 | 博客 | 软件 | 架构 | Java "> 
    <link rel="shortcut icon" href="http://www.shutdown.cn/img/favicon.ico" />
    <link rel="apple-touch-icon" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link rel="apple-touch-icon-precomposed" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link href="http://www.shutdown.cn/js/vendor/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/main.css" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/syntax.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
     fancybox: true, 
    motion: true
  };
</script>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left page-home  ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-meta  custom-logo ">

  <div class="custom-logo-site-title">
    <a href="http://www.shutdown.cn"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">天地维杰网</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">人如秋鸿来有信，事若春梦了无痕</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
    <ul id="menu" class="menu">
      
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/redis/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-full"></i> <br />Redis
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/java/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-coffee"></i> <br />java
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/linux/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-linux"></i> <br />linux
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/daily/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bug"></i> <br />日常问题
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/spring/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-child"></i> <br />Spring和Springboot
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/spring/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-fire"></i> <br />Mac相关
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/middleware/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-gavel"></i> <br />中间件
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jiagou/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-rocket"></i> <br />架构
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/python/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-ship"></i> <br />python
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/front/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bolt"></i> <br />前端
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jvm/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-balance-scale"></i> <br />JVM
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/post/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/about/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于
          </a>
        </li>
      
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger"> <i class="menu-item-icon fa fa-search fa-fw"></i> <br /> 搜索</a>
      </li>
    </ul>
    <div class="site-search">
      <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>

    </div>
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
<section id="posts" class="posts-expand">
  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">
      <h1 class="post-title" itemprop="name headline">
        <a class="post-title-link" href="http://www.shutdown.cn/post/bigkey/" itemprop="url">
        
        </a>
      </h1>
      <div class="post-meta">
      <span class="post-time">
<span class="post-meta-item-icon">
    <i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">时间：</span>
<time itemprop="dateCreated" datetime="2016-03-22T13:04:35+08:00" content="0001-01-01">
    0001-01-01
</time>
</span> 
      
      
       <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读：</span>
<span class="leancloud-visitors-count">4065 字 ~20分钟</span>
</span>
      </div>
    </header>
    <div class="post-body" itemprop="articleBody">
    

    

<p><em>By Yanquan</em></p>

<h2 id="preface">Preface</h2>

<p>When using <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">Redis</a>, we often encounter BigKey and HotKey. If not detected and processed in time, BigKey and HotKey are likely to degrade service performance, deteriorate user experience, and even cause large-scale system failures.</p>

<h2 id="definition-of-bigkey-and-hotkey">Definition of BigKey and HotKey</h2>

<p>We can often see the definitions of BigKey and HotKey in Guideline for Developing With Redis in companies, or in numerous articles about Redis best practices on the Internet. Even though the criteria for judging BigKey and HotKey are different, it is clear that the dimensions of judging are the same. <strong>BigKey is usually determined by the data size and number of members</strong>, while <strong>HotKey is determined by the frequency and number of requests Redis receives</strong>.</p>

<h3 id="definition-of-bigkey">Definition of BigKey</h3>

<p>Generally, we call a key that contains large size of data or a large number of members and lists as BigKey. There are some examples to help you fully understand the characteristics of BigKey, find as below.</p>

<ul>
<li>A STRING key whose size of value is 5 MB (the data is too large).</li>
<li>A LIST key with 20,000 elements (the number of elements in the list is excessive).</li>
<li>A ZSET key with 10,000 members (the number of members is excessive).</li>
<li>A HASH key whose size is 100MB even if only contains 1,000 members (the size of the key is too large).</li>
</ul>

<p>It should be noted that the definition of BigKey might be different according to actual use cases and business scenarios of Redis. This is to say that you should judge taking all factors into consideration. In given examples, you can see some specific numbers for the size, members, and elements in a key, which is not a common definition of a BigKey, it&rsquo;s only to simplify the explanation, cannot be regarded as a standard in fact.</p>

<h3 id="definition-of-hotkey">Definition of HotKey</h3>

<p>When the workload of access to a key is significantly higher than that of other keys, we can call it a HotKey. To help you better understand what HotKeys looks like, here are some examples, please check as below.</p>

<ul>
<li>The total workload of access per second of a Redis instance is 10,000, while that of one key reaches 7,000. (Obviously, this key is a HotKey whose access is significantly higher than that of other keys.)</li>
<li>A HASH key with thousands of members and a total size of 1MB receives a large amount of HGETALL requests each second. (In this case, we call it a HotKey since accesses to one key cost significantly more bandwidth than that of other keys.)</li>
<li>A ZSET key with tens of thousands of members receives a large number of ZRANGE requests each second. (It&rsquo;s clear that the CPU run time is significantly higher than that spent on requests of other keys. Similarly, we can say this kind of key with large CPU consuming is a HotKey.)</li>
</ul>

<h2 id="problems-caused-by-bigkey-and-hotkey">Problems Caused by BigKey and HotKey</h2>

<p>When using <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">Redis</a>, BigKey and HotKey bring various problems. The most common ones are performance degradation, access timeout, access skew and data skew.</p>

<h3 id="typical-problems-caused-by-bigkey">Typical Problems Caused by BigKey</h3>

<ul>
<li>Clients get delayed responses and it feels like the Redis is slowing down.</li>
<li>The Redis memory usage keeps growing which triggers OOM, or write blocking and eviction of important keys occurs because of reaching the maxmemory.</li>
<li>Access skew occurs which may cause a Redis instance to reach the performance bottleneck, so that the whole cluster also reaches the performance bottleneck. In this case, the memory usage of one node in Redis Cluster usually far exceeds that of other nodes because of access requsts for BigKeys on it, and the minimum granularity of data migration in Redis Cluster is key that the memory on that node cannot be balanced. This is to say the problem cannot be resolved unless you find a method to divide BigKeys into small keys.</li>
<li>All services the Redis should be offering are affected as Redis is getting slower, which is all because read requests on a BigKey occupy all the bandwidth of Redis.</li>
<li>Synchronization interruption or failover occurs because of long time blocking of primary database when deleting a BigKey.</li>
</ul>

<h3 id="typical-problems-caused-by-hotkey">Typical Problems Caused by HotKey</h3>

<ul>
<li>HotKeys usually have long CPU run time, which deteriorates Redis performance and affects other requests.</li>
<li>Hotspot on some Redis nodes/machines, instead of on keys that sharding to different Redis nodes, often prevent you from taking full advantage of your Redis Cluster. As the memory/cpu load of these nodes will be quite heavy, while other nodes are not efficiently used.</li>
<li>As for panic buying and flash sales scenarios, oversold often occurs because the number of read requests for inventory on keys of corresponding goods is too much beyond the instance performance that the Redis cannot handle.</li>
<li>The traffic on HotKeys suddenly surges to the maximum threshold the Redis can tolerate, even causing the cache service to crash, which is commonly referred to as a Redis avalanche. If this is the case, a large number of requests will directly hit backend database, causing a high load to the database layer that the database may be unable to withstand and downtime, thus affecting the business.</li>
</ul>

<h2 id="common-causes-of-bigkey-and-hotkey">Common Causes of BigKey and HotKey</h2>

<p>Insufficient business planning, incorrect use of <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">Redis</a>, accumulation of invalid data, and sudden increase in access can cause BigKey and HotKey issues. For example:</p>

<p>\1) <strong>BigKey</strong>: Use Redis for inappropriate data types can introduce BigKey problems. For example, using String keys to store large binary files will make the values of the keys too large.</p>

<p>\2) <strong>BigKey</strong>: Insufficient planning and design before business launch and no proper sharding policies or split plans to divide members in an individual key to multiple keys, resulting in an excessive number of members in a particular key.</p>

<p>\3) <strong>BigKey</strong>: No regular cleanup on invalid data in HASH keys, resulting in a continuous increase of members in HASH keys, which may bring BigKey problems.</p>

<p>\4) <strong>HotKey</strong>: Unexpected increase of access traffic owing to hot products, hot news, KOL (Key Opinion Leader) live streaming event or an online games battle that invloves a large number of players.</p>

<p>\5) <strong>BigKey</strong>: Logical failures on business side that prevents LIST keys from being consumed, which result in an increasing number of members in the corresponding Key with no trend to decrease.</p>

<h2 id="dicover-bigkey-and-hotkey-in-redis">Dicover BigKey and HotKey in Redis</h2>

<h3 id="discover-bigkeys">【Discover BigKeys】</h3>

<p>It&rsquo;s not that difficult to discover BigKeys and HotKeys since there are many ways and means to analyze keys in Redis and to find out &ldquo;problem&rdquo; keys, such as built-in functions, open source tools of Redis, and Key Analysis functions in CloudDBA which you can find on the <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">ApsaraDB for Redis</a> console.</p>

<h3 id="discover-bigkey-and-hotkey-with-built-in-functions-of-redis">Discover BigKey and HotKey with Built-in Functions of Redis</h3>

<p>Some built-in commands and tools in Redis can help us find these problem keys. If you already have a clear analysis target, for example, there are some specious keys in your mind that might be the BigKey and HotKey, run the following commands to analyze.</p>

<h4 id="analyze-keys-by-using-redis-built-in-commands">Analyze keys by using Redis built-in commands</h4>

<ul>
<li>[Built-in command] <code>debug object &lt;key_name&gt;</code> (not recommended)</li>
</ul>

<p>You may choose to use the debug object command to analyze the keys. This command can analyze the key according to the incoming object (the key name) and return a variety of information, where the value of serializedlength is the serialization length of the key. You can choose to use this value to determine whether the corresponding key is a BigKey according to your determination criteria.</p>

<p><img src="https://yqintl.alicdn.com/b9a1ea6b15053dcc25be22c98f0e0d6ba43e5510.png" alt="2" /></p>

<p>It should be noted that the serialization length of the key is not equal to its actual size in memory. In addition, debug object is a debugging command and costs a lot to run, it&rsquo;s generally regarded as a command in high risk. It blocks other requests during its its run time, in other words, the Redis is out of service until its execution is completed. The serialization length of the incoming object (key name) determines the time occupied, the larger the key is then the more time it spends. Therefore, this command is not recommended to use in production environments to analyze BigKey.</p>

<ul>
<li>[Built-in command] <code>memory usage &lt;key_name&gt;</code> (not recommended)</li>
</ul>

<p>Redis has provided the MEMORY USAGE command since the version 4.0 to help you analyze the memory usage of keys. Even if its execution cost is lower than the debug object command, it still risks blocking when analyzing BigKey, because its time complexity is O(N),</p>

<ul>
<li>[Built-in command] <code>strlen, hlen, scard, zcard, llen, xlen</code> (recommended)</li>
</ul>

<p>We recommend analyzing keys in a less risky way. Redis provides different commands to get the length or number of members of keys with different data types, as shown in the following table:</p>

<p><img src="https://yqintl.alicdn.com/17a9ff8357e6d53183fe62137dc79979542d1e96.png" alt="3" /></p>

<p>By using the preceding Redis built-in commands, we can easily and safely analyze keys without affecting online services. However, the length it results usually doesn&rsquo;t equal to a key&rsquo;s memory use, so it can only be used for reference.</p>

<h4 id="discover-bigkeys-by-using-the-bigkeys-parameter-in-redis-cli">Discover BigKeys by using the BigKeys parameter in redis-cli</h4>

<p>If you do not have a clear target key for analysis but want to find out the BigKey in Redis, you can use redis-cli to achieve this goal by adding &lsquo;&ndash;BigKeys&rsquo; in the end.</p>

<p>[example] <code>redis-cli -h xxx -p xxx -a xxx --bigKeys</code></p>

<p><img src="https://yqintl.alicdn.com/1144e17b0d337a2554fdadb6b767f009c57f6ae4.png" alt="4" />
<img src="https://yqintl.alicdn.com/b085a816d87fd5d7e9518da596f841b1eb00ff61.png" alt="5" /></p>

<p>Redis provides the BigKeys parameter to enable redis-cli to analyze all keys in the entire Redis instance in a traversal manner and return a standard summary report. It&rsquo;s convenient and safe, but it&rsquo;s also very obvious to see that the analysis results cannot be customized.</p>

<p>The BigKeys parameter can only output the largest keys of all six Redis data types respectively. If you want to analyze only the STRING keys or find the HASH keys with more than 10 members, then it&rsquo;s impossible to achive by using the BigKeys parameter. What you can turn to if customized report is really in need? There are some open source projects on GitHub that can implement the enhanced version of BigKeys parameter so that the results can be customized according to the configuration. In addition, you can write a python or other scripts with a loop for all data types, using all commands listed in the table above, combining with scan functions to realize a BigKey analysis tool at the Redis instance level.</p>

<p>Similarly, this solution returns a result that is not so accurate and real-time, it&rsquo;s only for reference.</p>

<h3 id="discover-hotkeys">【Discover HotKeys】</h3>

<h4 id="discover-hotkeys-by-using-hotkeys-parameter-in-redis-cli">Discover HotKeys by using HotKeys parameter in redis-cli</h4>

<p>Redis has provided the HotKeys parameter since the version 4.0 to facilitate instance-level HotKey analysis. It can return the number of times that all keys have been accessed but the prerequisite before using is to set the maxmemory-policy to &lsquo;allkeys-lfu&rsquo;, which is only supported after Redis 4.0 and later versions.</p>

<p><img src="https://yqintl.alicdn.com/ec2d7a8494b08ae33e5bba1b7d9753a2eea1f78c.png" alt="6" /></p>

<h4 id="discover-hotkeys-from-the-business-layer">Discover HotKeys from the business layer</h4>

<p>Every access to Redis comes from the business layer. This means that we can record, asynchronously summarize, and analyze the access to Redis by adding corresponding codes to the business layer. In this way, you can accurately analyze HotKeys in real time, but at the expense of business code simplicity.</p>

<h4 id="discover-hotkeys-by-using-monitor-command-for-emergency">Discover HotKeys by using monitor command for emergency</h4>

<p>The monitor command of Redis can print all requests in Redis according to the fact, including access time, client IP, commands, and keys. In emergency, we can execute the monitor command for a short period of time and redirect the output to the file because it causes extra cost of CPU, memory and network. After terminating the monitor command, HotKeys during this period can be found by classifying and analyzing the requests in the file.</p>

<p><img src="https://yqintl.alicdn.com/221526514b3b1ce53875450a3783f3dfae984541.png" alt="7" />
<img src="https://yqintl.alicdn.com/eeaf865e681d7dd2bacb947f89b95adec15418d1.png" alt="8" /></p>

<p>As we mentioned before, the monitor command consumes the CPU, memory, and network resources of <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">ApsaraDB for Redis</a>. Therefore, for a Redis with a high workload, the monitor command may make things worse. Meanwhile, the timeliness of this asynchronous collection and analysis solution is poor, and the accuracy of the analysis depends on the execution duration of the monitor command. So, the accuracy of the result is not good enough in most online scenarios where the command cannot be executed for a long time.</p>

<h3 id="discover-bigkeys-by-using-open-source-tools">Discover BigKeys by Using Open Source Tools</h3>

<p>The popularity of Redis enables us to easily find a large number of open source solutions to solve the current problems we are facing, such as getting accurate analysis reports without affecting online services.</p>

<h4 id="use-redis-rdb-tools-to-discover-bigkeys-in-a-customized-way">Use redis-rdb-tools to discover BigKeys in a customized way</h4>

<p>The redis-rdb-tools is great if you want to accurately analyze the real memory usage of all keys in a Redis instance according to your own standards. It also can avoid disrupting online services, and you can get a concise, easy-to-understand report after the analysis finishes.</p>

<p>Redis rdstools allows you to perform customized analysis on RDB files of Redis. Since the analysis of RDB files works offline, it has no impact on online services. This is its biggest advantage but also its biggest disadvantage because offline analysis represents poor timeliness of analysis results. For a large RDB file, the analysis may last a long time.</p>

<h3 id="discover-bigkeys-and-hotkeys-by-using-the-key-analysis-service-on-public-cloud">Discover BigKeys and HotKeys by using the Key Analysis Service on Public Cloud</h3>

<p>For some public cloud service vendors, you can find one-click functions like &lsquo;Key Analysis Service&rsquo;, which allows you to analyze all the keys in the Redis instance in real time to discover the current and historical presence of BigKeys and HotKeys. In addition, it helps you know which BigKeys and HotKeys have appeared in the running timeline of Redis, so that you can have a comprehensive and accurate judgment on the running status of the entire Redis instance.</p>

<h4 id="clouddba-on-the-apsaradb-for-redis-console">CloudDBA on the ApsaraDB for Redis console</h4>

<p><a href="https://www.alibabacloud.com/product/das">CloudDBA</a> is an intelligent service for Alibaba Cloud database services (ApsaraDB). For ApsaraDB for Redis, it supports real-time analysis and discovery of BigKeys and HotKeys.</p>

<p>The Key Analysis Service is a kernel based function, which can directly discover and output information about BigKeys and HotKeys from the Redis kernel layer. It captures information from kernel which is the brain of the Redis and where all things organized, in other words, the data comes from the original source, therefore, the result is accurate and efficient. And because there is no extra calculating involved just some simple information capturing, it almost has no impact on performance. You can use this function by clicking &ldquo;Key Analysis&rdquo; under CloudDBA, as shown in figure 1-1:</p>

<p><img src="https://yqintl.alicdn.com/3b3a9e6189678b6d44ec2350650848f61a151cee.png" alt="9" />
Figure 1-1: CloudDBA on the ApsaraDB for Redis console</p>

<p>There are two tabs on the page of Key Analysis,&lsquo;Real-time&rsquo; and &lsquo;History&rsquo;, which allows you to analyze keys in the corresponding Redis instance in different time dimensions:</p>

<ul>
<li><strong>Real-time</strong>: Analyze the current instance immediately and display all the existing BigKeys and HotKeys.</li>
<li><strong>History</strong>: Display BigKeys and HotKeys that have appeared in the instance recently. On the History page, all BigKeys and HotKeys that have appeared are recorded, even if these keys no longer exist now. This function can well reflect the historical status of keys in Redis and help trace the history problems or problems with damaged scenes.</li>
</ul>

<p><img src="https://yqintl.alicdn.com/ade053cebaa3deeedac70dfa413eb2a89664bbd0.png" alt="10" /></p>

<h2 id="managing-bigkeys-and-hotkeys">Managing BigKeys and HotKeys</h2>

<p>Now, we have found the problematic keys in <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">Redis</a> through various means, it is time to resolve to prevent potential problems in the future.</p>

<h3 id="common-methods-for-dealing-with-bigkey">Common Methods for Dealing with BigKey</h3>

<h4 id="split-bigkey">Split BigKey</h4>

<p>For a string type BigKey, you can consider splitting it into multiple key values. For hash or list types, consider splitting them into multiple hash or list types. But you should ensure that the number of members of each key is within a reasonable range. To avoid uneven memory space, the splitting plan of BigKeys plays a significant especially for a Redis Cluster.</p>

<h4 id="clean-up-bigkey">Clean up BigKey</h4>

<p>Choose the right storage for your data is very important, particularly you can store data that is not suitable for Redis to other storage media and delete in Redis. As mentioned before, BigKeys may cause interruption to Redis cluster synchronization, so when deleting a key, it&rsquo;s better to use UNLINK command which can slowly and gradually clean up the incoming keys in a non-blocking way and it&rsquo;s provided since Redis 4.0. Through UNLINK, you can safely delete all kinds of BigKeys.</p>

<h4 id="monitor-the-memory-usage-level-of-redis-at-all-times">Monitor the memory usage level of Redis at all times</h4>

<p>The sudden occurrence of a BigKey problem can often catch us off guard. Therefore, finding and dealing with it before any further problems is an important means to keep the service stable. We can monitor the system and set a reasonable memory alarm threshold for Redis to remind us that BigKeys may be generated at this time. For example, alarm will be sent when Redis memory usage exceeds 70% or Redis memory growth rate exceeds 20% in one hour.</p>

<p>Through monitoring, we can solve the problem before it occurs. For example, when the failure of the consumer program of LIST causes the number of members in a list to grow continuously and no trend to decrease, we can turn alarms into warnings so the owner of the module may notice and fix the problem in time, by which we can avoid failures.</p>

<h4 id="regularly-clean-up-invalid-data">Regularly clean up invalid data</h4>

<p>For example, when we incrementally write a large amount of data to a HASH key, ignoring the timeliness of these data. These accumulated invalid data will cause the generation of a BigKey. You can clean up the invalid data by using scheduled tasks. HSCAN and HDEL are recommended to use, by which invalid data can be cleaned up without blocking.</p>

<h4 id="use-alibaba-cloud-tair-enterprise-edition-of-redis-to-avoid-tedious-work-of-invalid-data-cleanup">Use Alibaba Cloud Tair (Enterprise Edition of Redis) to avoid tedious work of invalid data cleanup</h4>

<p>You may have too many HASH keys, and a large number of invalid members needs to be cleaned up. For this scenario, scheduled tasks can no longer clean up invalid data in a timely manner. However, you can use <a href="https://www.alibabacloud.com/help/doc-detail/145957.htm">Alibaba Cloud&rsquo;s Tair</a> to solve such problems well.</p>

<p>Tair is the <a href="https://www.alibabacloud.com/help/doc-detail/145957.htm">Enterprise Edition of Alibaba Cloud ApsaraDB for Redis</a>. It provides a large number of additional advanced features except for all the features of ApsaraDB for Redis, including the high-performance features.</p>

<p>TairHash is a hash data type that allows you to set the expiration time and version for a field. Not only does It support a wide range of data interfaces and provide high processing performance like Redis Hash, but it also breaks the hash restriction that a hash key can only have expiration time in addtion to its value, and apparently it supports both expiration time and version setting for a TarHash key. This greatly improves the flexibility of the hash data and simplifies business code in many scenarios.</p>

<p>TairHash uses the efficient Active Expire algorithm to achieve the function of discovering and deleting expired data with almost no impact on the response time. The reasonable use of such advanced functions can liberate a large number of Redis O&amp;M and fault handling work and reduce the complexity of the business code. By doing so, O&amp;M personnel can devote their effort to other more valuable work, and R&amp;D personnel can have more time to focus on business code.</p>

<h3 id="common-methods-for-dealing-with-hotkeys">Common Methods for Dealing with HotKeys</h3>

<h4 id="copy-hotkeys-in-the-redis-cluster">Copy HotKeys in the Redis Cluster</h4>

<p>As mentioned before, the minimum migration granularity is key, when the memory usage of a particular node in a Redis Cluster increased to a high level because of a HotKey, it can not be back to normal unless you can split the HotKey into pieces and distribute to other nodes. If you are facing such scenario, you can copy the corresponding HotKeys and migrate them to other nodes. For example, you can copy three keys with exactly the same content of the HotKey &lsquo;foo&rsquo; and name them &lsquo;foo2&rsquo;, &lsquo;foo3&rsquo;, and &lsquo;foo4&rsquo;. Then, migrate these three copies to other nodes to share the workload of a single node.</p>

<p>However the disadvantage of this solution is obvious that the code needs to be modified by linkage and key copy brings data consistency challenges. That is, compared with updating one key, you need to update multiple keys at the same time now. In many cases, this is recognized as a temporary solution for some difficult environment.</p>

<h4 id="use-read-write-splitting-architecture">Use read/write splitting architecture</h4>

<p>If HotKeys are generated from read requests, read/write splitting is a good solution. When using the read/write splitting architecture, the read request workload on each Redis node can be decreased by continuously adding secondary nodes.</p>

<p>However, this solution increases the complexity of business code and the complexity of the Redis cluster architecture. For example, for Redis layer, on the one hand, forwarding layers (such as Proxy and LVS) is needed now for multiple secondary nodes to implement load balancing. On the other hand, considering with high availability of the service, increased node failure rate and node tolerance should be taken into consideration when adding more secondary nodes. The changes of the Redis cluster architecture bring greater challenges to monitoring, O&amp;M, and failure processing.</p>

<p>However, all these are extremely simple in Alibaba Cloud <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">ApsaraDB for Redis</a> which provides out-of-box services. At the same time, when business grows, Alibaba Cloud&rsquo;s <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">ApsaraDB for Redis</a> allows users to adjust the cluster architecture by changing configurations. For example, the primary/secondary architecture can be changed to read/write splitting architecture, the read/write splitting architecture can be changed to a cluster, the primary/secondary architecture can be changed to a cluster that supports read/write splitting, and Redis Community Edition can be directly changed to Redis Enterprise Edition (Tair) that supports a large number of advanced features.</p>

<p>The read/write splitting architecture can be used for dealing with HotKey issues but it also has shortcomings. In scenarios with a large number of requests, the read/write splitting architecture will incur an inevitable delay, that&rsquo;s where dirty data may be read. Therefore, the read/write splitting architecture is not appropriate in scenarios where both read and write workload is high and high data consistency is required.</p>

<h4 id="use-the-proxy-query-cache-feature-of-alibaba-cloud-tair">Use the Proxy Query Cache feature of Alibaba Cloud Tair</h4>

<p><a href="https://www.alibabacloud.com/help/doc-detail/216309.htm">Proxy Query Cache</a> is one of the enterprise-level features of Alibaba Cloud Tair (Redis Enterprise Edition). Its principle is shown in figure 2-1:</p>

<p><img src="https://yqintl.alicdn.com/c78049ee21e941caa59749712b1b6b2325220533.png" alt="11" />
Figure 2-1: Tair QueryCache principle</p>

<p>Alibaba Cloud <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">ApsaraDB for Redis</a> identifies hotkeys in instances based on efficient sorting and statistical algorithms. After enabling this function, Proxy servers will cache requests and corresponding query results based on the rules you set. Proxy servers cache only request and response data of a HotKey, instead of the entire key. If a proxy server receives a duplicate request within the validity period, the proxy server directly returns a response to the client without the need to interact with backend data shards. This improves the read speed and reduces the performance impact of HotKeys on data shards to avoid request skew.</p>

<p>So far, the same request from the client no longer needs to interact with the Redis behind Proxy. Instead, Proxy returns the data directly. The access request to the HotKey is processed by multiple proxy servers instead of a single Redis node, greatly reducing the HotKey workload on one particular Redis node. Moreover, the Proxy Query Cache function of Tair also provides a large number of commands to facilitate users to view and manage HotKeys. For example, run the querycache keys command to view all cached HotKeys, and run querycache listall to obtain all cached commands.</p>

<p><img src="https://yqintl.alicdn.com/9d754c65c6b430906c95bde0214024a67e7e6e20.png" alt="12" /></p>

<p>Combining Key Analysis Service in CloudDBA and Tair Proxy Query Cache feature, using ApsaraDB for Redis can reduce your cost of O&amp;M and improve R&amp;D efficiency.</p>

<h4 id="use-global-distributed-cache-for-redis-on-alibaba-cloud">Use Global Distributed Cache for Redis on Alibaba Cloud</h4>

<p>For HotKeys with frequent write instead of frequent read access over and over, then traditional Redis read/write splitting and cluster structures have nothing to do for resolving this kind of HotKey issues. What you need now is Global Distributed Cache feature which can extend the write capability of Redis by parallel writes upon a same key on distributed nodes, reducing the write workload to a particular node.</p>

<p><a href="https://www.alibabacloud.com/help/doc-detail/71881.htm">Global Distributed Cache for Redis of Alibaba Cloud</a>, also known as Global Replica, is an active geo-redundancy database system that is developed based on <a href="https://www.alibabacloud.com/product/apsaradb-for-redis">ApsaraDB for Redis</a>. It is ideal for business scenarios in which multiple sites in different regions provide services at the same time. It helps enterprises quickly realize similar active geo-redundancy architecture to Alibaba. <a href="https://www.alibabacloud.com/help/doc-detail/71881.htm">Global Distributed Cache for Redis</a> solves the cross-region and cross-country active problems. In addition, as it supports distributed write on up to three nodes, it can be used to improve write performance as well at up to three times. The architecture of <a href="https://www.alibabacloud.com/help/doc-detail/71881.htm">Global Distributed Cache for Redis</a> is shown in figure 2-2:</p>

<p><img src="https://yqintl.alicdn.com/bc439159da70675ac1cdb9178d1d2a87357cb016.png" alt="13" />
Figure 2-2: Architecture of Global Distributed Cache for Redis</p>

<p>Compared with traditional Redis synchronization middleware, <a href="https://www.alibabacloud.com/help/doc-detail/71881.htm">Global Distributed Cache for Redis</a> features high reliability, high throughput, low latency, and high synchronization accuracy.</p>

    </div>
    <footer class="post-footer">
     

     <div class="post-nav">
    <div class="post-nav-next post-nav-item">
    
        <a href="http://www.shutdown.cn/post/apt-get-update%E5%87%BA%E7%8E%B0no_pubkey%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/" rel="next" title="">
        <i class="fa fa-chevron-left"></i> 
        </a>
    
    </div>

    <div class="post-nav-prev post-nav-item">
    
        <a href="http://www.shutdown.cn/post/bigkey%E5%88%A0%E9%99%A4%E9%97%AE%E9%A2%98/" rel="prev" title="">
         <i class="fa fa-chevron-right"></i>
        </a>
    
    </div>
</div>
      
     
     
     






    </footer>
  </article>
</section>

          </div>
        </div>
        <div class="sidebar-toggle">
  <div class="sidebar-toggle-line-wrap">
    <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
  </div>
</div>
<aside id="sidebar" class="sidebar">
  <div class="sidebar-inner">

    <section class="site-overview sidebar-panel  sidebar-panel-active ">
      <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
        src="http://www.shutdown.cn/img/author.jpg"
        alt="不与天斗Domino" />
    <p class="site-author-name" itemprop="name">不与天斗Domino</p>
    <p class="site-description motion-element" itemprop="description"> 
        Programmer &amp; Architect</p>
</div>
      <nav class="site-state motion-element">
    <div class="site-state-item site-state-posts">
      <a href="http://www.shutdown.cn/post/">
        <span class="site-state-item-count">173</span>
        <span class="site-state-item-name">日志</span>
      </a>
    </div>
    <div class="site-state-item site-state-categories">    
        <a href="http://www.shutdown.cn/categories/">      
         
        <span class="site-state-item-count">10</span>
        
        <span class="site-state-item-name">分类</span>
        
        </a>
    </div>

    <div class="site-state-item site-state-tags">
        <a href="http://www.shutdown.cn/tags/">
         
        <span class="site-state-item-count">63</span>
        
        <span class="site-state-item-name">标签</span>
        </a>
    </div>
</nav>
      
      

      

      <div class="links-of-blogroll motion-element inline">
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=&amp;m=0&amp;s=220&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33&amp;bv=35" async="async"></script>
</div>

    </section>
    
  </div>
</aside>

      </div>
    </main>
   
    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  <span itemprop="copyrightYear">  &copy; 
  2013 - 2022</span>
  <span class="with-love"><i class="fa fa-heart"></i></span>
  <span class="author" itemprop="copyrightHolder">天地维杰网</span>
  <span class="icp" itemprop="copyrightHolder"><a href="https://beian.miit.gov.cn/" target="_blank">京ICP备13019191号-1</a></span>
</div>
<div class="powered-by">
  Powered by - <a class="theme-link" href="http://gohugo.io" target="_blank" title="hugo" >Hugo v0.63.2</a>
</div>
<div class="theme-info">
  Theme by - <a class="theme-link" href="https://github.com/xtfly/hugo-theme-next" target="_blank"> NexT
  </a>
</div>


      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
      <span id="scrollpercent"><span>0</span>%</span>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/fastclick/lib/fastclick.min.js?v=1.0.6"></script> 
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="http://www.shutdown.cn/js/vendor/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>

<script src="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.pack.js?v=2.1.5"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/utils.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/motion.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/affix.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/schemes/pisces.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/scrollspy.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/post-details.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/toc.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/bootstrap.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
      inlineMath: [ ['$','$'] ],
      displayMath: [ ['$$','$$'] ],
      processEscapes: true
    },
    "HTML-CSS": { fonts: ["TeX"] }
  });
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML' async></script>
</body>
</html>